package com.cyn.controller.rabbitmq.config;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.core.RabbitTemplate.ConfirmCallback;
import org.springframework.amqp.rabbit.core.RabbitTemplate.ReturnCallback;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


@Component
public class Send  {
 
	@Autowired
	private RabbitTemplate rabbitTemplate;
	
 
	// 消息发送到交换机回调
	final ConfirmCallback confirmCallback = new ConfirmCallback() {
 
		@Override
		public void confirm(CorrelationData correlationData, boolean ack, String cause) {
			System.err.println("correlationData：" + correlationData);
			String massageID = correlationData.getId();
			System.err.println("===massageID：" + massageID);
			if (ack) {
				System.err.println("ACK：" + ack );
			} else {
				System.err.println("ACK：" + ack+ "===cause：" + cause);
			}
		}
	};
 
	// 交换机到队列报错执行回调
	final ReturnCallback returnCallback = new ReturnCallback() {
 
		@Override
		public void returnedMessage(Message message, int replyCode, String replyText, String exchange,
				String routingKey) {
			System.err.println("==========消息主体=========" + message);
			System.err.println("==========消息主体=========" + replyCode);
			System.err.println("==========描述=========" + replyText);
			System.err.println("==========交换机=========" + exchange);
			System.err.println("==========路由键=========" + routingKey);
 
		}
	};
	
	public void SendOrder(Order order) throws Exception {
		rabbitTemplate.setConfirmCallback(confirmCallback);
		rabbitTemplate.setReturnCallback(returnCallback);
		
		CorrelationData correlationData = new CorrelationData();
		correlationData.setId(order.getMessageId());
//		rabbitTemplate.convertAndSend("order-exchange", "order.add", order, correlationData);
		rabbitTemplate.convertAndSend("lonelyDirectExchange", "TestDirectRouting", order, correlationData);
		Thread.sleep(1000);
 
	}

	public void sendsend(){
		String messageId = String.valueOf(UUID.randomUUID());
		String messageData = "message: lonelyDirectExchange test message ";
		String createTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
		Map<String, Object> map = new HashMap<>();
		map.put("messageId", messageId);
		map.put("messageData", messageData);
		map.put("createTime", createTime);
		rabbitTemplate.setConfirmCallback(confirmCallback);
		rabbitTemplate.setReturnCallback(returnCallback);
		rabbitTemplate.convertAndSend("lonelyDirectExchange", "TestDirectRouting", map);
	}
 
	
 
}